﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SuperQuiz.Logic;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace SuperQuiz.View
{
    public sealed partial class StarPointsControl : UserControl
    {
        public int ScoredPoints { get; set; }

        public StarPointsControl(int scoredPoints)
        {
            ScoredPoints = scoredPoints;
            this.InitializeComponent();
            this.Loaded += StarPointsControl_Loaded;
            this.WinningPoints.Completed += AnimationCompleted;
            this.LosingPoints.Completed += AnimationCompleted;
            this.KeepingPoints.Completed += AnimationCompleted;
        }

        async void StarPointsControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (ScoredPoints == 0)
            {
                text.Text = String.Format("+{0}", ScoredPoints);
                this.KeepingPoints.Begin();
            }
            else if (ScoredPoints > 0)
            {
                text.Text = String.Format("+{0}", ScoredPoints);
                this.WinningPoints.Begin();
            }
            else
            {
                text.Text = String.Format("-{0}", ScoredPoints);
                this.LosingPoints.Begin();
            }

            if (QuizApplication.Instance.Settings.PlaySounds)
            {
                var sound = new MediaElement();
                var parent = (Panel)this.Parent;
                parent.Children.Add(sound);
                sound.AudioCategory = AudioCategory.GameEffects;
                sound.AutoPlay = true;
                sound.Visibility = Visibility.Collapsed;
                sound.MediaEnded += PlayCompleted;
                sound.Source = new Uri("ms-appx:/SuperQuiz/Assets/Sounds/ting.mp3");
            }
        }

        void PlayCompleted(object sender, object e)
        {
            var parent = (Panel)((FrameworkElement)sender).Parent;
            parent.Children.Remove((UIElement)sender);
        }

        void AnimationCompleted(object sender, object e)
        {
            var parent = (Panel)this.Parent;
            parent.Children.Remove(this);
        }
    }
}
